<?php
namespace app\modules\controllers;

use yii\web\Controller;
use app\modules\models\Admin;
use Yii;

class PublicController extends Controller
{
    public function actionLogin()
    {
        $this->layout = false;
        $model = new Admin;
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            if ($model->login($post)) {
                $this->redirect(['default/index']);
                Yii::$app->end();
            }
        }
        return $this->render("login", ['model' => $model]);
    }

    public function actionLogout()
    {
        Yii::$app->admin->logout(false);
        return $this->goback();
    }

    public function actionSeekpassword()
    {
        $this->layout = false;
        $model = new Admin;
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            if ($model->seekPass($post)) {
                Yii::$app->session->setFlash('info', '电子邮件已经发送成功，请查收');
            }
        }
        return $this->render("seekpassword", ['model' => $model]);
    }

    //找回密码
    public function actionMailchangepass(){
        $this->layout= false;
        $time = Yii::$app->request->get("timestamp");
        $adminuser = Yii::$app->request->get('adminuser');
        $token = Yii::$app->request->get('token');
        $model =  new Admin();
        $mytoken = $model->createToken($adminuser,$time);
        if($token != $mytoken){
            $this->redirect(['public/login']);
            Yii::$app->end();
        }
        if(time() - $time > 300){
            $this->redirect(['public/login']);
            Yii::$app->end();
        }
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            if($model->changePass($post)){
                Yii::$app->session->setFlash('info','修改密码成功');
            };
        }
        $model->adminuser = $adminuser;
        return $this->render("mailchangepass",['model'=>$model]);
    }


    //错误页面设置，跟config/web.php下面配置配合使用
    public function actionError()
    {
        $this->layout = false;
        $exception = Yii::$app->errorHandler->exception;
        $data['status']=$exception->statusCode;
        $data['message']=$exception->getMessage();
        return $this->render("error",['data'=>$data]);
    }

}
